#!/bin/bash -x
BaseDir=$(dirname $(readlink -f "$0"))
LocalAppHome=$(dirname $BaseDir)

# Load env from /proc/1/environ
cat /proc/1/environ | tr '\0' '\n' | awk -F= '{gsub(/\./, "___", $1); print "export \"" $1 "\"=\"" $2 "\""}' > /tmp/proc_1_environ
source /tmp/proc_1_environ
rm -f /tmp/proc_1_environ

####################################################################################################################
# Initialize environment variables
####################################################################################################################
if [ "$APP_NAME" == "" ]; then
    export APP_NAME="sysom"
fi

if [ "$APP_HOME" == "" ]; then
    export APP_HOME=/usr/local/sysom
fi

# For rpm build phase only
# 1. Normally, this environment variable is the empty string
# 2. In rpm build stage, this environment variable is "%{build_root}"
if [ "$INSTALL_PREFIX" == "" ]; then
    export INSTALL_PREFIX=""
fi

export SERVER_HOME=${INSTALL_PREFIX}${APP_HOME}/server
export NODE_HOME=${INSTALL_PREFIX}${APP_HOME}/node
export SCRIPT_HOME=${INSTALL_PREFIX}${APP_HOME}/init_scripts
export WEB_HOME=${INSTALL_PREFIX}${APP_HOME}/web
export DEPS_HOME=${INSTALL_PREFIX}${APP_HOME}/deps
export ENVIRONMENT_HOME=${INSTALL_PREFIX}${APP_HOME}/environment
export MICROSERVICE_HOME=${SERVER_HOME}
export MICROSERVICE_SCRIPT_HOME=${SCRIPT_HOME}/server
export GLOBAL_VIRTUALENV_HOME=${ENVIRONMENT_HOME}/virtualenv

if [ "$SERVER_LOCAL_IP" == "" ]; then
    local_ip=$(ip -4 route | grep "link src" | grep -v "docker" | grep -v "podman" | awk -F"link src " '{print $2}' | awk '{print $1}' | head -n 1)
    export SERVER_LOCAL_IP=$local_ip
fi

if [ "$SERVER_PUBLIC_IP" == "" ]; then
    export SERVER_PUBLIC_IP=$SERVER_LOCAL_IP
fi

if [ "$SERVER_PORT" == "" ]; then
    export SERVER_PORT=80
fi

if [ "$LOG_HOME" == "" ]; then
    export LOG_HOME=/var/log/sysom
fi
mkdir -p $LOG_HOME

if [ "$CONF_HOME" == "" ]; then
    export CONF_HOME=/etc/sysom
    export SYSOM_CONF=${CONF_HOME}/config.yml
fi
mkdir -p $CONF_HOME

# if [ "$DB_MYSQL_HOST" == "" ]; then
#     export DB_MYSQL_HOST=localhost
# fi

# if [ "$DB_MYSQL_PORT" == "" ]; then
#     export DB_MYSQL_PORT=3306
# fi

# if [ "$DB_MYSQL_USERNAME" == "" ]; then
#     export DB_MYSQL_USERNAME=sysom
# fi

# if [ "$DB_MYSQL_PASSWORD" == "" ]; then
#     export DB_MYSQL_PASSWORD=sysom_admin
# fi

# if [ "$DB_MYSQL_DATABASE" == "" ]; then
#     export DB_MYSQL_DATABASE=sysom
# fi

# if [ "$REDIS_HOST" == "" ]; then
#     export REDIS_HOST=localhost
# fi

# if [ "$REDIS_PORT" == "" ]; then
#     export REDIS_PORT=6379
# fi

# if [ "$REDIS_USERNAME" == "" ]; then
#     export REDIS_USERNAME=""
# fi

# if [ "$REDIS_PASSWORD" == "" ]; then
#     export REDIS_PASSWORD=""
# fi

# Deploy env list
if [ "$DEPLOY_ENV_LIST" == "" ]; then
    local_environment_dir=${LocalAppHome}/environment
    export DEPLOY_ENV_LIST=$(echo $(ls $local_environment_dir) | sed 's/ /,/g')
fi
if [ "$DEPLOY_ENV_EXCLUDE" != "" ]; then
    DEPLOY_ENV_EXCLUDE=$(echo $DEPLOY_ENV_EXCLUDE | sed 's/,/\n/g' | awk '{print length(), $0 | "sort -n  -r" }' | awk '{print $2}' | tr '\n' ',' | sed 's/.$//')
    targets=(${DEPLOY_ENV_EXCLUDE//,/ })
    env_list=$DEPLOY_ENV_LIST
    for target in ${targets[*]}; do
        env_list=$(echo $env_list | sed "s/${target}//g" | sed 's/,,/,/g')
    done
    export DEPLOY_ENV_LIST=$env_list
fi
export DEPLOY_ENV_LIST_REVERT=$(echo $DEPLOY_ENV_LIST | sed 's/,/\n/g' | tac | tr '\n' ',' | sed 's/.$//')

# Deploy deps list
if [ "$DEPLOY_DEPS_LIST" == "" ]; then
    local_deps_install_dir=${LocalAppHome}/deps
    export DEPLOY_DEPS_LIST=$(echo $(ls $local_deps_install_dir) | sed 's/ /,/g')
fi
if [ "$DEPLOY_DEPS_EXCLUDE" != "" ]; then
    DEPLOY_DEPS_EXCLUDE=$(echo $DEPLOY_DEPS_EXCLUDE | sed 's/,/\n/g' | awk '{print length(), $0 | "sort -n  -r" }' | awk '{print $2}' | tr '\n' ',' | sed 's/.$//')
    targets=(${DEPLOY_DEPS_EXCLUDE//,/ })
    deps_list=$DEPLOY_DEPS_LIST
    for target in ${targets[*]}; do
        deps_list=$(echo $deps_list | sed "s/${target}//g" | sed 's/,,/,/g')
    done
    export DEPLOY_DEPS_LIST=$deps_list
fi
export DEPLOY_DEPS_LIST_REVERT=$(echo $DEPLOY_DEPS_LIST | sed 's/,/\n/g' | tac | tr '\n' ',' | sed 's/.$//')

# Deploy server list
if [ "$DEPLOY_SERVER_LIST" == "" ]; then
    local_microservice_install_dir=${LocalAppHome}/sysom_server
    if [ ! -d ${local_microservice_install_dir} ]; then
        local_microservice_install_dir=${LocalAppHome}/server
    fi
    export DEPLOY_SERVER_LIST=$(echo $(ls $local_microservice_install_dir) | sed 's/ /,/g')
fi
if [ "$DEPLOY_SERVER_EXCLUDE" != "" ]; then
    DEPLOY_SERVER_EXCLUDE=$(echo $DEPLOY_SERVER_EXCLUDE | sed 's/,/\n/g' | awk '{print length(), $0 | "sort -n  -r" }' | awk '{print $2}' | tr '\n' ',' | sed 's/.$//')
    targets=(${DEPLOY_SERVER_EXCLUDE//,/ })
    service_list=$DEPLOY_SERVER_LIST
    for target in ${targets[*]}; do
        service_list=$(echo $service_list | sed "s/${target}//g" | sed 's/,,/,/g')
    done
    export DEPLOY_SERVER_LIST=$service_list
fi
export DEPLOY_SERVER_LIST_REVERT=$(echo $DEPLOY_SERVER_LIST | sed 's/,/\n/g' | tac | tr '\n' ',' | sed 's/.$//')

####################################################################################################################
# Subcommands
####################################################################################################################

ProgName=$(basename $0)
BaseDir=$(dirname $(readlink -f "$0"))
subcommand=$1

sub_help() {
    echo "Usage: $ProgName <subcommand> [options]"
    echo "Subcommands:"
    echo "    install      Install SysOM module"
    echo "    uninstall    Uninstall SysOM module"
    echo "    update       Update SysOM module"
    echo "    start        Start SysOM module"
    echo "    stop         Stop SysOM module"
    echo "    init         Init SysOM module"
    echo "    clear        Clear SysOM module"
    echo "    list         List all SysOM module"
    echo ""
    echo "For help with each subcommand run:"
    echo "$ProgName <subcommand> -h|--help"
    echo ""
}

sub_func() {
    bash +x ${BaseDir}/sysom_${subcommand}.sh $@
}

case $subcommand in
"" | "-h" | "--help")
    sub_help
    ;;
*)
    shift
    sub_func $@
    if [ $? -ne 0 ]; then
        echo "Error: '$subcommand' is not a known subcommand." >&2
        echo "       Run '$ProgName --help' for a list of known subcommands." >&2
        exit 1
    fi
    ;;
esac
